package com.ArrayStack;

/**
 * 使用数组模拟栈
 * 定义top表示栈顶，初始化为-1
 * 入栈：top++; stack[top] = value;
 * 出栈：vaule = stack[top]; top--; return value;
 */
public class ArrayStack {
    private int maxSize;
    private int stack[]; //用数组模拟栈，
    private int top = -1;

    public ArrayStack(int maxSize){
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }
    /**
     * 判断栈满top ? maxSize -1
     */
    public boolean isFull(){
        return top == maxSize -1 ;
    }

    /**
     * 判断栈空：top = -1
     */
    public boolean isEmpty(){
        return top == -1;
    }
    /**
     * 入栈
     */
    public void push(int value){
        //判断栈是否已满
        if(isFull()){
            System.out.println("堆栈已满");
            return;
        }
        top++;
        stack[top]=value;
    }

    /**
     * 出栈：先获取栈顶元素，再移动栈顶指针。
     */
    public int pop(){
        //判断栈是否为空
        if(isEmpty()){
            throw new RuntimeException("栈为空，无法出栈");
        }
        int value = stack[top];
        top--;
        return value;
    }

    /**
     * 遍历栈：从栈顶显示数据
     */
    public void list(){
        if(isEmpty()){
            throw new RuntimeException("栈为空");
        }
        for(int temp = top;temp > -1;temp--){
            System.out.println("stack["+temp+"] = "+stack[temp]);
        }
    }
}
